package saxion.speelveld.spaceengineer.view.tabs;

import java.util.ArrayList;

import saxion.speelveld.spaceengineer.R;
import saxion.speelveld.spaceengineer.controller.buildingsSimpleAdapter;
import saxion.speelveld.spaceengineer.model.Building;
import saxion.speelveld.spaceengineer.model.Game;
import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TabHost;

public class CurrentBuildings extends LinearLayout
{

	private Game game;

	private ArrayList<Building> currentBuildings;

	private ListView lvCurrentBuildings;

	private TabHost tabHost;

	public CurrentBuildings(Context context, AttributeSet attrs)
	{
		super(context, attrs);
		this.Initialize(context);
	}

	public CurrentBuildings(Context context)
	{
		super(context);
		this.Initialize(context);
	}

	public void Initialize(Context context)
	{
		LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		inflater.inflate(R.layout.tab_current_buildings, this);
		lvCurrentBuildings = (ListView) this.findViewById(R.id.currentBuildingsList);
	}

	/*
	 * Fill list from buildings to current Buildings.
	 */
	public void fillList()
	{
		// huidige gebouwen toezeggen aan this.currentBuildings
		this.currentBuildings = this.game.getBuildings();

		if (currentBuildings != null)
		{
			buildingsSimpleAdapter adapter = new buildingsSimpleAdapter(this.getContext(), currentBuildings);
			lvCurrentBuildings.setAdapter(adapter);
			lvCurrentBuildings.setOnItemClickListener(new NavigateToBuildingOnClick());
		}
	}

	public void setGameModel(Game game)
	{
		this.game = game;

		this.fillList();
	}

	public void setTabHost(TabHost tabhost)
	{
		this.tabHost = tabhost;
	}

	public void switchTabInActivity(int indexTabToSwitchTo)
	{
		UpgradeScreen parentActivity;
		parentActivity = (UpgradeScreen) this.getParent();
	}

	public void switchTab(int tab)
	{
		tabHost.setCurrentTab(tab);
		// tabHost = getTabHost();
	}

	private class NavigateToBuildingOnClick implements OnItemClickListener
	{

		@Override
		public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3)
		{
			Building b = game.getBuildings().get(arg2);
			game.setViewPointToMiddleOf(b.getBuildingPointInFieldX(), b.getBuildingPointInFieldY(), b.getWidth(),
				b.getHeight());
			game.setSelectedTile(game.getField()[b.getBuildingPointInFieldX()][b.getBuildingPointInFieldY()]);
			tabHost.setCurrentTab(3);
		}
	}
}
